﻿using Microsoft.Win32;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Windows.Forms;
using System.Xml.Linq;
using System.Xml;
using System;
using U8Login;
using YonYou.U8.IN.Framework;
using System.Xml.XPath;
using MSXML2;

namespace Yonyou.U8.QuickImport
{
    public class CommonUtil
    {
        public static bool CheckAuthValid(clsLoginClass login, string authId)
        {
            if (string.IsNullOrEmpty(authId))
            {
                return true;
            }
            if (login.IsAdmin)
            {
                return true;
            }
            bool result = false;
            try
            {
                short result2 = 0;
                if (!string.IsNullOrEmpty(login.cIYear) && !short.TryParse(login.cIYear, out result2))
                {
                    result2 = (short)DateTime.Now.Year;
                }
                if (!login.TaskExec(authId, 1, result2))
                {
                    return false;
                }
                result = true;
                return result;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                return result;
            }
        }

        public static bool CheckExSelfDefineItem(string name, string path, string archXml, object login, ref string msg)
        {
            try
            {
                bool result = false;
                object[] array = new object[5];
                Type typeFromProgID = Type.GetTypeFromProgID("U8Common.iCommon");
                if (typeFromProgID == null)
                {
                    MessageHelper.ShowMessage("组件未注册错误", "系统未注册组件U8Common.iCommon!");
                    return false;
                }
                object target = typeFromProgID.InvokeMember(null, BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.CreateInstance, null, null, null);
                array[0] = name;
                array[1] = path;
                array[2] = archXml;
                array[3] = login;
                array[4] = string.Empty;
                ParameterModifier parameterModifier = new ParameterModifier(5);
                parameterModifier[4] = true;
                ParameterModifier[] modifiers = new ParameterModifier[1] { parameterModifier };
                object obj = typeFromProgID.InvokeMember("CheckExcelExDefineItems", BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.InvokeMethod, null, target, array, modifiers, null, null);
                if (obj != null)
                {
                    msg = array[4].ToString();
                    result = Convert.ToBoolean(obj.ToString());
                }
                return result;
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }

        public static bool FindOpenedWorkBook(string name, bool isTopMost)
        {
            string empty = string.Empty;
            if (GetInstalledExcelType() == ExcelType.OfficeExcel)
            {
                name = string.Format("Microsoft Excel - {0}", name);
                empty = "EXCEL";
            }
            else
            {
                name = string.Format("WPS 表格 - [{0}]", name);
                empty = "ET";
            }
            Process[] processesByName = Process.GetProcessesByName(empty);
            foreach (Process process in processesByName)
            {
                if (process.MainWindowTitle.IndexOf(name) == 0)
                {
                    if (isTopMost)
                    {
                        IntPtr mainWindowHandle = process.MainWindowHandle;
                        Win32Api.SetForegroundWindow(mainWindowHandle);
                        Win32Api.SetActiveWindow(mainWindowHandle);
                        Win32Api.SetWindowPos(mainWindowHandle, Win32Api.HWND_TOPMOST, 0, 0, 0, 0, 3u);
                        Win32Api.SetWindowPos(mainWindowHandle, Win32Api.HWND_NOTOPMOST, 0, 0, 0, 0, 3u);
                    }
                    return true;
                }
            }
            return false;
        }

        public static string GetBillAuthId(string name)
        {
            string result = string.Empty;
            string filename = Path.Combine(Context.U8Path, "ExcelModel\\ModelList.xml");
            XmlDocument xmlDocument = new XmlDocument();
            xmlDocument.Load(filename);
            ModelListFilter(xmlDocument);
            XmlNode xmlNode = xmlDocument.SelectSingleNode("//menu[@name='" + name + "']");
            if (xmlNode != null)
            {
                result = xmlNode.Attributes["authId"].InnerText;
            }
            return result;
        }

        public static string GetFileName(string path)
        {
            if (string.IsNullOrEmpty(path))
            {
                return string.Empty;
            }
            string[] array = path.Split("\\".ToCharArray());
            int num = array.Length;
            return array[num - 1];
        }

        public static ExcelType GetInstalledExcelType()
        {
            RegistryKey registryKey = null;
            registryKey = Registry.ClassesRoot.OpenSubKey("CLSID\\{00024500-0000-0000-C000-000000000046}");
            if (registryKey != null)
            {
                return ExcelType.OfficeExcel;
            }
            if (registryKey == null)
            {
                registryKey = Registry.ClassesRoot.OpenSubKey("CLSID\\{00020906-0000-4b30-A977-D214852036FE}");
            }
            if (registryKey != null)
            {
                return ExcelType.WPSExcel;
            }
            return ExcelType.Nothing;
        }

        public static string GetUniqueLoginKey(clsLoginClass login)
        {
            string[] array = login.DataSource.Split("@".ToArray());
            string text = array[array.Length - 1];
            return login.dbServerName + "_" + text + login.cUserId + "_KEY";
        }

        public static string LoadStyleSheet(string name, object login)
        {
            try
            {
                string text = string.Empty;
                object[] array = new object[2];
                Type typeFromProgID = Type.GetTypeFromProgID("U8Common.iCommon");
                if (typeFromProgID == null)
                {
                    MessageHelper.ShowMessage("组件未注册错误", "系统未注册组件U8Common.iCommon!");
                    return string.Empty;
                }
                object target = typeFromProgID.InvokeMember(null, BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.CreateInstance, null, null, null);
                array[0] = name;
                array[1] = login;
                object obj = typeFromProgID.InvokeMember("LoadStyleSheet", BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.InvokeMethod, null, target, array);
                if (obj != null)
                {
                    IXMLDOMDocument2 val = (IXMLDOMDocument2)((obj is IXMLDOMDocument2) ? obj : null);
                    if (val != null)
                    {
                        text = val.xml;
                    }
                }
                if (string.IsNullOrEmpty(text))
                {
                    throw new Exception("获取导入模板StyleSheet失败！");
                }
                XmlDocument xmlDocument = new XmlDocument();
                xmlDocument.LoadXml(text);
                string text2 = Context.QIPath + "\\Xml\\StyleSheet.xsl";
                xmlDocument.Save(text2);
                return text2;
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }

        public static void ModelListFilter(XmlDocument xmlDoc)
        {
            XmlNodeList xmlNodeList = xmlDoc.SelectNodes(".//menu");
            List<XmlNode> list = new List<XmlNode>();
            foreach (XmlNode item in xmlNodeList)
            {
                XmlNode namedItem = item.Attributes.GetNamedItem("support");
                if (namedItem != null && !namedItem.Value.ToUpper().Equals("QI"))
                {
                    list.Add(item);
                }
            }
            foreach (XmlNode item2 in list)
            {
                item2.ParentNode.RemoveChild(item2);
            }
        }

        public static void ModelListFilter(XDocument xmlDoc)
        {
            IEnumerable<XElement> enumerable = xmlDoc.XPathSelectElements(".//menu");
            List<XElement> list = new List<XElement>();
            foreach (XElement item in enumerable)
            {
                XAttribute xAttribute = item.Attribute("support");
                if (xAttribute != null && !xAttribute.Value.ToUpper().Equals("QI"))
                {
                    list.Add(item);
                }
            }
            foreach (XElement item2 in list)
            {
                item2.Remove();
            }
        }

        public static void ModelListFilter(XElement element)
        {
            IEnumerable<XElement> enumerable = element.XPathSelectElements(".//menu");
            List<XElement> list = new List<XElement>();
            foreach (XElement item in enumerable)
            {
                XAttribute xAttribute = item.Attribute("support");
                if (xAttribute != null && !xAttribute.Value.ToUpper().Equals("QI"))
                {
                    list.Add(item);
                }
            }
            foreach (XElement item2 in list)
            {
                item2.Remove();
            }
        }

        public static List<string> ModelListFilter(Context context)
        {
            XmlDocument xmlDocument = new XmlDocument();
            xmlDocument.Load(context.ExcelModelPath + "\\ModelList.xml");
            XmlNodeList xmlNodeList = xmlDocument.SelectNodes(".//menu");
            List<string> list = new List<string>();
            List<XmlNode> list2 = new List<XmlNode>();
            foreach (XmlNode item in xmlNodeList)
            {
                XmlNode namedItem = item.Attributes.GetNamedItem("support");
                if (namedItem != null && !namedItem.Value.ToUpper().Equals("QI"))
                {
                    list2.Add(item);
                    continue;
                }
                namedItem = item.Attributes.GetNamedItem("filename");
                if (namedItem != null)
                {
                    list.Add(namedItem.Value);
                }
            }
            foreach (XmlNode item2 in list2)
            {
                item2.ParentNode.RemoveChild(item2);
            }
            return list;
        }

        public static XmlDocument ReadStrategy(bool breport, Context context)
        {
            XmlDocument xmlDocument = new XmlDocument();
            xmlDocument.Load(context.QICurImportStrategy + "\\StrategyList.xml");
            XmlDocument xmlDocument2 = new XmlDocument();
            XmlNode xmlNode = xmlDocument.SelectSingleNode("//menu[@default='true']");
            if (xmlNode != null)
            {
                string value = xmlNode.Attributes.GetNamedItem("id").Value;
                if (value.Equals("默认方案"))
                {
                    xmlDocument2.Load(Context.QIPath + "\\ImportStrategy\\" + value + ".xml");
                    for (int i = 0; i < xmlDocument2.DocumentElement.ChildNodes.Count; i++)
                    {
                        for (int j = 0; j < xmlDocument2.DocumentElement.ChildNodes.Item(i).ChildNodes.Count; j++)
                        {
                            xmlDocument2.DocumentElement.ChildNodes.Item(i).ChildNodes.Item(j).Attributes.GetNamedItem("filename").Value = context.QICurrentModelPath + "\\" + xmlDocument2.DocumentElement.ChildNodes.Item(i).ChildNodes.Item(j).Attributes.GetNamedItem("filename").Value;
                        }
                    }
                }
                else
                {
                    xmlDocument2.Load(context.QICurImportStrategy + "\\" + value + ".xml");
                }
            }
            else
            {
                xmlDocument2.Load(context.QICurImportStrategy + "\\DefaultImportStrategy.xml");
            }
            if (breport && xmlDocument2.SelectNodes("//menu").Count == 0)
            {
                MessageBox.Show("本次导入没有任何数据项被选中，请选择需要导入的数据项!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
                return null;
            }
            XmlDocument xmlDocument3 = new XmlDocument();
            xmlDocument3.Load(Context.QIPath + "\\ImportStrategy\\ImportParameter.xml");
            XmlNode xmlNode2 = xmlDocument2.SelectSingleNode("//import");
            xmlNode2.Attributes.Item(0).Value = xmlDocument3.DocumentElement.FirstChild.Attributes.Item(0).Value;
            xmlNode2.Attributes.Item(1).Value = xmlDocument3.DocumentElement.FirstChild.Attributes.Item(1).Value;
            xmlNode2.Attributes.Item(2).Value = xmlDocument3.DocumentElement.FirstChild.Attributes.Item(2).Value;
            return xmlDocument2;
        }

        public static XmlDocument ReadStrategy(bool isInSolution, bool breport, Context context)
        {
            XmlDocument xmlDocument = new XmlDocument();
            if (isInSolution)
            {
                XmlDocument xmlDocument2 = new XmlDocument();
                xmlDocument2.Load(context.QICurImportStrategy + "\\StrategyList.xml");
                XmlNode xmlNode = xmlDocument2.SelectSingleNode("//menu[@default='true']");
                if (xmlNode != null)
                {
                    string value = xmlNode.Attributes.GetNamedItem("id").Value;
                    if (value.Equals("默认方案"))
                    {
                        xmlDocument.Load(Context.QIPath + "\\ImportStrategy\\" + value + ".xml");
                        for (int i = 0; i < xmlDocument.DocumentElement.ChildNodes.Count; i++)
                        {
                            for (int j = 0; j < xmlDocument.DocumentElement.ChildNodes.Item(i).ChildNodes.Count; j++)
                            {
                                xmlDocument.DocumentElement.ChildNodes.Item(i).ChildNodes.Item(j).Attributes.GetNamedItem("filename").Value = context.QICurrentModelPath + "\\" + xmlDocument.DocumentElement.ChildNodes.Item(i).ChildNodes.Item(j).Attributes.GetNamedItem("filename").Value;
                            }
                        }
                    }
                    else
                    {
                        xmlDocument.Load(context.QICurImportStrategy + "\\" + value + ".xml");
                    }
                }
                else
                {
                    xmlDocument.Load(context.QICurImportStrategy + "\\DefaultImportStrategy.xml");
                }
            }
            else
            {
                xmlDocument.Load(context.QICurImportStrategy + "\\DefaultImportStrategy.xml");
            }
            if (breport && xmlDocument.SelectNodes("//menu").Count == 0)
            {
                MessageBox.Show("本次导入没有任何数据项被选中，请选择需要导入的数据项!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
                return null;
            }
            XmlDocument xmlDocument3 = new XmlDocument();
            xmlDocument3.Load(Context.QIPath + "\\ImportStrategy\\ImportParameter.xml");
            XmlNode xmlNode2 = xmlDocument.SelectSingleNode("//import");
            xmlNode2.Attributes.Item(0).Value = xmlDocument3.DocumentElement.FirstChild.Attributes.Item(0).Value;
            xmlNode2.Attributes.Item(1).Value = xmlDocument3.DocumentElement.FirstChild.Attributes.Item(1).Value;
            xmlNode2.Attributes.Item(2).Value = xmlDocument3.DocumentElement.FirstChild.Attributes.Item(2).Value;
            return xmlDocument;
        }
    }
}